﻿using System.Collections.Generic;

namespace ElevatorDispatching
{
    /// <summary>
    /// 默认的楼层群组生成器实现
    /// </summary>
    public class DefaultFloorGroupBuilder : IFloorGroupBuilder
    {
        private int _lowestFloorId;

        private int _highestFloorId;

        private ICollection<int> _excludedFloorIds;

        /// <summary>
        /// 构建默认的楼层群组生成器
        /// </summary>
        /// <param name="lowestFloorId">最低的楼层编号</param>
        /// <param name="highestFloorId">最高的楼层编号</param>
        public DefaultFloorGroupBuilder(int lowestFloorId, int highestFloorId)
        {
            _lowestFloorId = lowestFloorId;
            _highestFloorId = highestFloorId;
            _excludedFloorIds = new SortedSet<int>();
        }

        /// <summary>
        /// 设置最低的楼层编号
        /// </summary>
        /// <param name="lowestFloorId">最低的楼层编号</param>
        /// <returns></returns>
        public IFloorGroupBuilder Lowest(int lowestFloorId)
        {
            _lowestFloorId = lowestFloorId;
            return this;
        }

        /// <summary>
        /// 设置最高的楼层编号
        /// </summary>
        /// <param name="highestFloorId">最高的楼层编号</param>
        /// <returns></returns>
        public IFloorGroupBuilder Highest(int highestFloorId)
        {
            _highestFloorId = highestFloorId;
            return this;
        }

        /// <summary>
        /// 设置跳过的楼层编号
        /// </summary>
        /// <param name="excludedFloorIdList">跳过的楼层编号</param>
        /// <returns></returns>
        public IFloorGroupBuilder Exclude(params int[] excludedFloorIdList)
        {
            foreach (var id in excludedFloorIdList)
            {
                _excludedFloorIds.Add(id);
            }
            return this;
        }

        /// <summary>
        /// 生成楼层群组
        /// </summary>
        /// <returns>生成的楼层群组</returns>
        public FloorGroup Build()
        {
            var floors = new List<Floor>();
            for (int i = _lowestFloorId; i <= _highestFloorId; i++)
            {
                if (i != 0 && !_excludedFloorIds.Contains(i))
                {
                    floors.Add(new Floor(i));
                }
            }
            if (floors.Count > 1) for (int i = 0; i < floors.Count - 1; i++)
                {
                    floors[i].UpperFloor = floors[i + 1];
                    floors[i + 1].LowerFloor = floors[i];
                }

            return new FloorGroup(floors);
        }
    }
}
